//
//  EditOwnerNameView.swift
//  ezyform
//
//  Created by Moennig Q on 1/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import RxGesture
class EditOwnerInfomationView: CreateJobBaseView {
    @objc dynamic var viewModel: EditOwnerInfomationViewModel!
    //View
    let propertyView = OwnerPropertyTypeView()
    var ownerTypeView: TextFieldWithRequiredView = {
        let view = TextFieldWithRequiredView()
        view.textField.clearButtonMode = .never
        return view
    }()
    //individual
    lazy var individualView = EditOwnerInfoForIndividualView()
    //commertial
    lazy var commertialView = EditOwnerInfoForCommertialView()
    
    override func setUpContentView(){
        //propery type
        contentView.addSubview(propertyView)
        propertyView.snp.makeConstraints { make in
            make.top.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        //1.first name title
        let companyTypeTitle = LabelWithRedStarView(R.string.localizable.ownerType())
        self.contentView.addSubview(companyTypeTitle)
        companyTypeTitle.snp.makeConstraints { (make) in
            make.top.equalTo(propertyView.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(propertyView)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //1.1.ownerTypeView
        ownerTypeView.textField.placeholder = "Please select"
        ownerTypeView.textField.isEnabled = false
        ownerTypeView.textField.showRightImageView("installation_list_search_down_arrow")
        self.contentView.addSubview(ownerTypeView)
        ownerTypeView.snp.makeConstraints { (make) in
            make.top.equalTo(companyTypeTitle.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(propertyView)
            make.height.greaterThanOrEqualTo(0)
        }

        self.continueBtn.setTitle(R.string.localizable.save(), for: UIControl.State.normal)
        //共用
        self.propertyView.selectPropertyTypeClosure = {[weak self] (type) in
            guard let strongSelf = self else { return  }
            strongSelf.viewModel.property_type = type
            strongSelf.setContentView(strongSelf.viewModel.owner_type)
            strongSelf.dealGSTValueByPropertyType()//重置GST的value
        }
        //点击owner type选择
        ownerTypeView.rx.tapGesture().when(.recognized).subscribe(onNext: {[weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.selectOwnerType()
        }).disposed(by: self.disposeBag)

    }
    
    func setData(_ model: EditOwnerInfomationViewModel){
        self.viewModel = model
        self.propertyView.setPropertyType(self.viewModel.property_type)
        self.ownerTypeView.textField.text = self.viewModel.owner_type_value
        //设置view和数据设置
        self.setContentView(self.viewModel.owner_type)
        //
        if model.editFlag{//编辑已经创建的job 信息
            self.validateAllRequiredFieldWhenEdit()
        }else{//初始化GST的值, 默认false
            self.dealGSTValueByPropertyType()
        }
        //save btn 是否可用
        self.checkEverythingValid()
    }
    //MARK: - 选择property type，调整gst的值，默认为false
    private func dealGSTValueByPropertyType(){
        if self.viewModel.property_type == .residential {
            if self.viewModel.owner_type == .individual {
                self.individualView.dealGSTValue(gstFlag: false)
            }else{
                self.commertialView.dealGSTValueByPropertyType(gstFlag: false)
            }
        }
    }
    //MARK: - 初始化GST的值，或调整property type或owner type要重置GST的值
    private func dealGSTValueByOwnerType(){
        if self.viewModel.owner_type == .individual {
            self.individualView.dealGSTValue(gstFlag: false)
        }
    }
    //MARK: - 切换individual或commertial view
    private func setContentView(_ type: OwnerType){
        if type == .individual {
            //移除commertial view
            if let _ = self.commertialView.superview{
                self.commertialView.removeFromSuperview()
            }
            //添加individual view
            if self.individualView.superview == nil{
                self.contentView.addSubview(self.individualView)
                self.individualView.snp.makeConstraints { make in
                    make.top.equalTo(ownerTypeView.snp.bottom).offset(Constant.TopBottomMargin)
                    make.left.right.equalTo(propertyView)
                    make.height.greaterThanOrEqualTo(0)
                    make.bottom.equalTo(-Constant.AllOutMargin)
                }
                
                self.individualView.setData(self.viewModel)
            }
        }else{
            //移除commertial view
            if let _ = self.individualView.superview{
                self.individualView.removeFromSuperview()
            }
            //添加icommertial view
            if self.commertialView.superview == nil{
                self.contentView.addSubview(self.commertialView)
                self.commertialView.snp.makeConstraints { make in
                    make.top.equalTo(ownerTypeView.snp.bottom).offset(Constant.TopBottomMargin)
                    make.left.right.equalTo(propertyView)
                    make.height.greaterThanOrEqualTo(0)
                    make.bottom.equalTo(-Constant.AllOutMargin)
                }
                self.commertialView.setData(self.viewModel)
            }
        }
    }
    //MARK: - 只用于已创建Job的信息编辑， 进入编辑界面如果save 按钮不可用，要给与相应提示
    private func validateAllRequiredFieldWhenEdit(){
        self.ownerTypeView.checkIfStandardValid()
        if self.viewModel.owner_type == OwnerType.individual{
            self.individualView.validateAllRequiredFieldWhenEdit()
        }else{
            self.commertialView.validateAllRequiredFieldWhenEdit()
        }
        
    }
    func selectOwnerType() {
        self.endEditing(true)
        let cellList = [CellModel(title: OwnerType.individual.rawValue),
                        CellModel(title: OwnerType.corporateBody.rawValue),
                        CellModel(title: OwnerType.governmentBody.rawValue),
                        CellModel(title: OwnerType.trustee.rawValue)]
        
        let actionSheetView = CustomActionSheet(title: R.string.localizable.selectOwnerType(), aCellArray: cellList, aCancelModel: CellModel(title: R.string.localizable.cancel()), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else { return  }
            let oldValue = strongSelf.viewModel.owner_type
            if row == 0 {//individual
                strongSelf.setOwnerType(OwnerType.individual)
                //从commertial切换为individual
                if oldValue != .individual {
                    strongSelf.dealGSTValueByOwnerType()
                }
            }else{
                if row == 1{//corporateBody
                    strongSelf.setOwnerType(OwnerType.corporateBody)
                }else if row == 2 {//governmentBody
                    strongSelf.setOwnerType(OwnerType.governmentBody)
                }else if row == 3 {//trustee
                    strongSelf.setOwnerType(OwnerType.trustee)
                }
                strongSelf.commertialView.toCheckABN()//切换到commertial重新校验下abn，处理gst的是否开启
                //从individual切换为commertial
                if oldValue == .individual{
                    strongSelf.dealGSTValueByOwnerType()
                }
            }
        }, aCancelClosure: nil)
        self.addSubview(actionSheetView)
    }
    //MARK: - 根据owner type切换view
    private func setOwnerType(_ type: OwnerType){
        self.ownerTypeView.textField.text = type.rawValue
        //value
        self.ownerTypeView.checkTextIfValid()
        self.viewModel.owner_type = type
        //
        self.setContentView(type)
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.header type
        let propertyTypeValid = self.viewModel.rx.observe(String.self, "property_type_value").map({($0 ?? "").count > 0}).share(replay: 1)
        //2.common for individual and other owner type
        let mobileValid = self.viewModel.rx.observe(String.self, "mobile").map({
            let data = $0 ?? ""
            if data.count > 0 && Tool().isValidPhone(phone: data){
                return true
            }else{
                return false
            }
        }).share(replay: 1)
        let emailValid = self.viewModel.rx.observe(String.self, "email").map({
            let data = $0 ?? ""
            if data.count > 0 && Tool().isValidEmail(emailStr: data){
                return true
            }else{
                return false
            }
        }).share(replay: 1)
        
        //2.individual owner type
        let individualOwnerTypeValid = self.viewModel.rx.observe(String.self, "owner_type_value").map({($0 ?? "") == OwnerType.individual.rawValue}).share(replay: 1)
        let firstNameValid = self.viewModel.rx.observe(String.self, "first_name").map({($0 ?? "").count > 0}).share(replay: 1)
        let surnameValid = self.viewModel.rx.observe(String.self, "surname").map({($0 ?? "").count > 0}).share(replay: 1)
        let coOwnerOptionalValid = self.viewModel.rx.observe(Bool.self, "co_owner_optional").map({$0 ?? false}).share(replay: 1)
        let coownerFirstNameValid = self.viewModel.rx.observe(String.self, "co_owner_first_name").map({($0 ?? "").count > 0}).share(replay: 1)
        let coownerSurnameValid = self.viewModel.rx.observe(String.self, "co_owner_surname").map({($0 ?? "").count > 0}).share(replay: 1)
        let coownerRelationShipValid = self.viewModel.rx.observe(String.self, "co_owner_relation_ship").map({($0 ?? "").count > 0}).share(replay: 1)
        //
        let individualInfoValid = Observable.combineLatest(
            firstNameValid,
            surnameValid,
            mobileValid,
            emailValid,
            coOwnerOptionalValid,
            coownerFirstNameValid,
            coownerSurnameValid,
            coownerRelationShipValid
          ) {
              if $0 && $1 && $2 && $3 && (!$4 || ($4 && $5 && $6 && $7)) {
                  return true
              }
              return false
          }
          .share(replay: 1)
        //3.other owner type
        let otherOwnerTypeValid = self.viewModel.rx.observe(String.self, "owner_type_value").map({
            let data = $0 ?? ""
            if data != OwnerType.individual.rawValue && data.count > 0 {
                return true
            }
            return false
        }).share(replay: 1)
        let abnValid = self.viewModel.rx.observe(Bool.self, "home_owner_abn_valid_flag").map({($0 ?? false)}).share(replay: 1)
        let companyNameValid = self.viewModel.rx.observe(String.self, "company_name").map({($0 ?? "").count > 0}).share(replay: 1)
        let representativeNameValid = self.viewModel.rx.observe(String.self, "owner_representative_name").map({($0 ?? "").count > 0}).share(replay: 1)
        let positionValid = self.viewModel.rx.observe(String.self, "owner_representative_position").map({($0 ?? "").count > 0}).share(replay: 1)
        let unitPriceValid = self.viewModel.rx.observe(String.self, "price_to_the_home_owner").map({($0 ?? "").count > 0}).share(replay: 1)
        let otherOwnerTypeInfoValid = Observable.combineLatest(
            otherOwnerTypeValid,
            abnValid,
            companyNameValid,
            mobileValid,
            emailValid,
            representativeNameValid,
            positionValid,
            unitPriceValid
          ) {
              if $0 && $1 && $2 && $3 && $4 && $5 && $6 && $7 {
                  return true
              }
              return false
          }
          .share(replay: 1)
        //3.everthing valid
        let everythingValid = Observable.combineLatest(
            propertyTypeValid,
            individualOwnerTypeValid,
            individualInfoValid,
            otherOwnerTypeInfoValid
        ) {
            if $0 && (($1 && $2) || $3){
                return true
            }
            return false
        }
          .share(replay: 1)
        //
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.continueBtn.enableBtn()
            }else{
                strongSelf.continueBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
}
